﻿/*
 * Copyright © 2020, Wuxi Safover Intelligent Technology Co., Ltd. All rights reserved.
 * 
 * 无锡安永智能科技有限公司版权所有，未经许可，不得用于商业用途
 * 
 * Visit: https://www.safover.com/ 
 */

using System;
using System.Threading;
using Safover.Lidar.DataContract;
using static Safover.LidarCollector.Managers.DeviceManager;

namespace Safover.LidarCollector.Managers
{
    internal class FixedScan: SingleScan
    {
        protected override string Name => "FixedScan";

        protected override LidarWorkMode LidarWorkMode => LidarWorkMode.Fixed;

        protected override LidarScanMode LidarScanMode => LidarScanMode.Fixed;

        internal FixedScan(PeriodicScanParams periodicScanParams) : base(periodicScanParams)
        { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="delaySeconds">采集结束后的等待时间</param>
        /// <param name="cacher"></param>
        /// <param name="handler"></param>
        /// <returns></returns>
        internal SingleScanResult Scan(//Stopwatch stopwatch, TimeSpan? timeAllowed,
            uint delaySeconds, DataCacher cacher, SingleCollectionWorkingStatusChangedEventHandler handler)
        {
            var horizontalAngle = DataCollector.LidarConfig.FixedHorizontalAngle;
            var verticalAngle = DataCollector.LidarConfig.FixedVertialAngle;

            Log.DebugWriteLine($"----- {Name}: Ready for {LidarWorkMode} step scan, fixed vertical angle = 【{verticalAngle}】, fixed horizontial angle = 【{horizontalAngle}】.");

            handler?.Invoke(new SingleCollectionWorkingStatusChangedEventArgs
            {
                IsSingleCollecting = true,
                SingleLidarWorkMode = LidarWorkMode,
                PercentageCompletion = .15f,
                Message = "Read",
                CountDownSecondsForNextFixedCollection = 0
            });

            if (!DeviceFactoryInstance.OpticalMaserDevice.StartLasar())
            {
                throw new OpticalMaserMalfunctionException($"{Name}: Failed to start optical maser.");
            }

            Log.DebugWriteLine($"{Name}: Lasar is on.");

            handler?.Invoke(new SingleCollectionWorkingStatusChangedEventArgs
            {
                IsSingleCollecting = true,
                SingleLidarWorkMode = LidarWorkMode,
                PercentageCompletion = .25f,
                Message = "Laser is on",
            });

            StartCatchingData(cacher, TimeSpan.FromSeconds(SingleAcquisitionTimeout));

            if (!DeviceFactoryInstance.OpticalMaserDevice.StopLasar())
            {
                throw new OpticalMaserMalfunctionException($"{Name}: Failed to stop optical maser.");
            }

            handler?.Invoke(new SingleCollectionWorkingStatusChangedEventArgs
            {
                IsSingleCollecting = false,
                SingleLidarWorkMode = LidarWorkMode,
                PercentageCompletion = .95f,
                Message = "Laser is off, Saving Data",
            });

            FinishSingleScan(cacher, startAngle: 0, endAngle: 0, horizontalAngle, verticalAngle);

            // 采集后等待时间
            //var waitSeconds = Convert.ToInt32(RuntimeConfigManager.Instance.LidarConfig.SingleScanEndDelayDuration.TotalSeconds);
            for (int i = (int)delaySeconds; i >= 0; i--)
            {
                if (!DataCollector.ShouldContinueCollection)
                {
                    return SingleScanResult.Interrupted;
                }

                handler?.Invoke(new SingleCollectionWorkingStatusChangedEventArgs
                {
                    IsSingleCollecting = false,
                    SingleLidarWorkMode = LidarWorkMode,
                    PercentageCompletion = 1,
                    CountDownSecondsForNextFixedCollection = i
                });
                Thread.Sleep(1000);
            }

            Log.DebugWriteLine($"[Thread={Thread.CurrentThread.Name}]: {LidarWorkMode}, single collection done.");

            //if (stopwatch != null && stopwatch.Elapsed >= timeAllowed)
            //{
            //    Log.DebugWriteLine($"[MultiScan.{lidarWorkMode}]: TotalScan duration finished.");
            //    return SingleScanResult.MultiModeTimeout;
            //}

            return SingleScanResult.Success;
        }

       
    }
}
